package com.nullpointer.xchatfinal;

import org.jivesoftware.smack.XMPPException;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.nullpointer.xchatfinal.libs.OpponentSurfaceView;
import com.nullpointer.xchatfinal.libs.OwnSurfaceView;
import com.nullpointer.xchatfinal.libs.OwnSurfaceView.CameraDataListener;
import com.nullpointer.xchatfinal.object.MessageContent.MsgType;
import com.nullpointer.xchatfinal.object.PrivateMessageContent;
import com.nullpointer.xchatfinal.object.User;
import com.nullpointer.xchatfinal.service.ChatService;
import com.nullpointer.xchatfinal.utils.Common;
import com.nullpointer.xchatfinal.utils.DataManager;
import com.nullpointer.xchatfinal.utils.KiraGameLog;
import com.quickblox.users.model.QBUser;
import com.quickblox.videochat.core.QBVideoChatController;
import com.quickblox.videochat.model.listeners.OnQBVideoChatListener;
import com.quickblox.videochat.model.objects.CallState;
import com.quickblox.videochat.model.objects.CallType;
import com.quickblox.videochat.model.objects.VideoChatConfig;

public class VideoCallActivity extends Activity {
	private OpponentSurfaceView vcTarget;
	private TextView tvName;
	private OwnSurfaceView vcMe;
	private ProgressBar pbLoading;
	private ImageButton ibEndCall;
	private ImageButton ibSwitchCamera;
	private VideoChatConfig videoChatConfig;
	private Integer targetID;
	private String targetName;
	private boolean isCaller = true;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		//DataManager.getInstance(this).setIsShowNotify(false);
		setContentView(R.layout.activity_video_call);
		findViewIDs();
		init();
		setEvent();
	}

	private void setEvent() {
		vcMe.setCameraDataListener(new CameraDataListener() {

			@Override
			public void onCameraDataReceive(byte[] data) {
				if (videoChatConfig != null
						&& videoChatConfig.getCallType() != CallType.VIDEO_AUDIO) {
					return;
				}
				QBVideoChatController.getInstance().sendVideo(data);
			}
		});
		ibSwitchCamera.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				vcMe.switchCamera();
			}
		});

		ibEndCall.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				QBVideoChatController.getInstance().finishVideoChat(
						videoChatConfig);
				vcTarget.clear();
				finish();
			}
		});

	}

	private void init() {
		videoChatConfig = getIntent().getParcelableExtra(
				VideoChatConfig.class.getCanonicalName());
		targetID = getIntent().getIntExtra(Common.ExtraKey.USER_ID, 0);
		targetName = getIntent().getStringExtra(Common.ExtraKey.USER_NAME);
		if (targetID == 0) {
			finish();
			return;
		}
		if (targetName != null) {
			tvName.setText(targetName);
		}
		isCaller = getIntent().getBooleanExtra(Common.ExtraKey.IS_CALLER, true);
		// Set video chat listener
		final App app = (App) getApplication();
		try {
			QBVideoChatController.getInstance().setQBVideoChatListener(
					app.getCurrentUser(), qbVideoChatListener);
			if (isCaller) {
				// Call target user
				QBUser targetUser = new QBUser();
				targetUser.setId(targetID);
				videoChatConfig = QBVideoChatController.getInstance()
						.callFriend(targetUser, CallType.VIDEO_AUDIO, null);
			} else {
				// Send accept video call request
				User user = DataManager.getInstance(this).getCurrentUser();
				String text = user.getName() + " has accepted the video chat";
				PrivateMessageContent privateMessageContent = new PrivateMessageContent(
						VideoCallActivity.this, text,
						MsgType.ACCEPT_VIDEO_CALL, Integer.toString(targetID));
				try {
					ChatService.getInstance().sendMessagePrivate(
							privateMessageContent, null);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

		} catch (XMPPException e) {
			e.printStackTrace();
			finish();
			return;
		}
	}

	OnQBVideoChatListener qbVideoChatListener = new OnQBVideoChatListener() {

		@Override
		public void onCameraDataReceive(byte[] videoData) {
			//
		}

		@Override
		public void onMicrophoneDataReceive(byte[] audioData) {
			QBVideoChatController.getInstance().sendAudio(audioData);
		}

		@Override
		public void onOpponentVideoDataReceive(final byte[] videoData) {
			vcTarget.render(videoData);
		}

		@Override
		public void onOpponentAudioDataReceive(byte[] audioData) {
			QBVideoChatController.getInstance().playAudio(audioData);
		}

		@Override
		public void onProgress(boolean progress) {
			// progressBar.setVisibility(progress ? View.VISIBLE : View.GONE);
		}

		@Override
		public void onVideoChatStateChange(CallState callState,
				VideoChatConfig receivedVideoChatConfig) {
			videoChatConfig = receivedVideoChatConfig;

			switch (callState) {
			case ON_CALL_START:
				KiraGameLog.d("onVideoChatStateChange ON_CALL_START");

				pbLoading.setVisibility(View.INVISIBLE);
				break;
			case ON_CANCELED_CALL:
				KiraGameLog.d("onVideoChatStateChange ON_CANCELED_CALL");
				videoChatConfig = null;
				// if (alertDialog != null && alertDialog.isShowing()) {
				// alertDialog.dismiss();
				// }
				// autoCancelHandler.removeCallbacks(autoCancelTask);

				break;
			case ON_CALL_END:
				KiraGameLog.d("onVideoChatStateChange ON_CALL_END");
				// clear opponent view
				vcTarget.clear();
				finish();
				break;
			case ACCEPT:
				KiraGameLog.d("onVideoChatStateChange ACCEPT");
				QBVideoChatController.getInstance().acceptCallByFriend(
						videoChatConfig, null);
				break;
			case ON_ACCEPT_BY_USER:
				KiraGameLog.d("onVideoChatStateChange ON_ACCEPT_BY_USER");

				QBVideoChatController.getInstance().onAcceptFriendCall(
						videoChatConfig, null);
				break;
			case ON_REJECTED_BY_USER:
				KiraGameLog.d("onVideoChatStateChange ON_REJECTED_BY_USER");

				pbLoading.setVisibility(View.INVISIBLE);
				break;
			case ON_CONNECTED:
				KiraGameLog.d("onVideoChatStateChange ON_CONNECTED");

				pbLoading.setVisibility(View.INVISIBLE);

				break;
			case ON_START_CONNECTING:
				KiraGameLog.d("onVideoChatStateChange ON_START_CONNECTING");
				break;
			case ON_DID_NOT_ANSWERED:
				KiraGameLog.d("onVideoChatStateChange ON_DID_NOT_ANSWERED");
				break;
			default:
				break;
			}
		}
	};

	private void findViewIDs() {
		vcTarget = (OpponentSurfaceView) findViewById(R.id.vc_target);
		tvName = (TextView) findViewById(R.id.tv_name);
		vcMe = (OwnSurfaceView) findViewById(R.id.vc_me);
		pbLoading = (ProgressBar) findViewById(R.id.pb_loading);
		ibEndCall = (ImageButton) findViewById(R.id.ib_end_call);
		ibSwitchCamera = (ImageButton) findViewById(R.id.ib_switch_camera);

	}

	@Override
	protected void onResume() {
		super.onResume();
		vcMe.reuseCamera();
	}

	@Override
	protected void onPause() {
		vcMe.closeCamera();
		super.onPause();
	}

	@Override
	protected void onStop() {
		QBVideoChatController.getInstance().finishVideoChat(videoChatConfig);
		super.onStop();
	}

}
